package com.tz.colawallet.basecode.base;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.trello.rxlifecycle.components.support.RxFragment;
import com.tz.colawallet.R;
import com.tz.colawallet.basecode.util.ToastUtil;
import com.tz.colawallet.bean.MessageEvent;
import com.wang.avi.AVLoadingIndicatorView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import static android.app.Activity.RESULT_OK;

/**
 * Created by JINAN on 2017/10/12.
 */

public abstract class BaseFragment extends RxFragment {

    /**
     * 是否可见状态
     */
    private boolean isVisible;
    /**
     * 标志位，View已经初始化完成。
     */
    private boolean isPrepared;
    /**
     * 是否第一次加载
     */
    private boolean isFirstLoad = true;

    private AVLoadingIndicatorView avLoadingView;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutResId(), container, false);
        bind(view);
        setup();
        initTitle(view);
        init(view);

        isFirstLoad = true;
        isPrepared = true;
        lazyLoad();
        return view;
    }


    /**
     * 返回视图id
     *
     * @return id
     */
    protected abstract int getLayoutResId();


    protected void bind(View view) {
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {/* Do something */}

    /**
     * 依赖注入
     */
    protected void setup() {
    }

    /**
     * 绑定ButterKnife
     *
     * @param view
     */
//    protected abstract void bindButterKnife(View view);

    /**
     * 初始化标题
     *
     * @param view
     */
    protected abstract void initTitle(View view);

    /**
     * 初始化视图
     *
     * @param view
     */
    protected abstract void init(View view);


    /**
     * 要实现延迟加载Fragment内容,需要在 onCreateView
     * isPrepared = true;
     */
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || !isFirstLoad) {
            //if (!isAdded() || !isVisible || !isFirstLoad) {
            return;
        }
        isFirstLoad = false;
        initData();
    }

    protected abstract void initData();


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 如果是与ViewPager一起使用，调用的是setUserVisibleHint
     *
     * @param isVisibleToUser 是否显示出来了
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    /**
     * 如果是通过FragmentTransaction的show和hide的方法来控制显示，调用的是onHiddenChanged.
     * 若是初始就show的Fragment 为了触发该事件 需要先hide再show
     *
     * @param hidden hidden True if the fragment is now hidden, false if it is not
     *               visible.
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    protected void onVisible() {
        lazyLoad();
    }

    protected void onInvisible() {
    }

    protected void showToast(int resId) {
        ToastUtil.showText(getActivity(), resId);
    }

    protected void showToast(String msg) {
        ToastUtil.showText(getActivity(), msg);
    }


    protected void switchActivity(Class<?> cls, Bundle extras) {
        Intent intent = new Intent(getActivity(), cls);
        if (extras != null) {
            intent.putExtras(extras);
        }
        startActivity(intent);
    }

    protected void switchActivity(Class<?> cls, Bundle extras, int flags) {
        Intent intent = new Intent(getActivity(), cls);
        if (extras != null) {
            intent.putExtras(extras);
        }
        intent.setFlags(flags);
        startActivity(intent);
    }

    protected void switchActivityAndFinish(Class<?> cls, Bundle extras) {
        switchActivity(cls, extras);
        getActivity().finish();
    }

    protected void switchActivityAndFinish(Class<?> cls, Bundle extras,
                                           int flags) {
        switchActivity(cls, extras, flags);
        getActivity().finish();
    }

    protected void switchActivityForResult(Class<?> cls, int requestCode,
                                           Bundle extras) {
        Intent intent = new Intent(getActivity(), cls);
        if (extras != null) {
            intent.putExtras(extras);
        }
        startActivityForResult(intent, requestCode);
    }

    protected void switchActivityForResult(Class<?> cls, int requestCode,
                                           Bundle extras, int flags) {
        Intent intent = new Intent(getActivity(), cls);
        if (extras != null) {
            intent.putExtras(extras);
        }
        intent.setFlags(flags);
        startActivityForResult(intent, requestCode);
    }

    protected void finishActivityForResult() {
        Intent intent = new Intent();
        getActivity().setResult(RESULT_OK, intent);
        getActivity().finish();
    }

    protected void finishActivityWithExtra(Bundle extras) {
        Intent intent = new Intent();
        if (extras != null) {
            intent.putExtras(extras);
        }
        getActivity().setResult(RESULT_OK, intent);
        getActivity().finish();
    }

    protected void switchActivityReorder2Front(Class<?> cls) {
        Intent intent = new Intent(getActivity(), cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
    }

    protected void switchFragment(Fragment fragment, int resId, Bundle extras) {
        if (extras != null) {
            fragment.setArguments(extras);
        }
        getActivity().getSupportFragmentManager().beginTransaction()
                .replace(resId, fragment).commit();
    }

    private Dialog progressDialog;

    /**
     * 加载框显示
     **/
    public void loading(boolean isLoading) {
        if (isLoading) {
            View loadingView = getActivity().getLayoutInflater().inflate(R.layout.item_loading, null);
            avLoadingView = loadingView.findViewById(R.id.av_loading_view);
            if (avLoadingView == null) {
                avLoadingView.show();
            }
            if (!avLoadingView.isShown()) {
                avLoadingView.show();
            }
        } else {
            if (avLoadingView != null && avLoadingView.isShown()) {
                avLoadingView.hide();
            }
        }
    }

}
